﻿using System;
using System.Collections.Generic;
using System.Net;

namespace Com.ZGH.Dns
{
    public class DnsQuestion : IElement
    {
        private DnsName query;
        private short queryType;
        private short queryClass;

        public DnsName Query
        {
            get { return query; }
            set { query = value; }
        }

        public short QueryType
        {
            get { return queryType; }
            set { queryType = value; }
        }

        public short QueryClass
        {
            get { return queryClass; }
            set { queryClass = value; }
        }

        public DnsQuestion()
        {
        }

        public int Size
        {
            get { return query.Size + 4; }
        }

        public DnsQuestion(DnsName query, short queryType, short queryClass)
        {
            this.query = query;
            this.queryType = queryType;
            this.queryClass = queryClass;
        }

        public byte[] ToBytes()
        {
            var bytes = new List<byte>();

            bytes.AddRange(query.ToBytes());

            bytes.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(queryType)));

            bytes.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(queryClass)));

            return bytes.ToArray();
        }

        public static DnsQuestion Parse(byte[] value,int start)
        {
            var question = new DnsQuestion();

            question.query = DnsName.Parse(value,start);

            question.queryType = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(value, start+ question.query.Size));

            question.queryClass = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(value,start+ question.query.Size+2));

            return question;
        }
    }
}
